class ProductController < ApplicationController
	before_filter :login_required
	layout "framework", :except=>[:product_info]
	def index
		@session[:rights] = buildMenu '产品管理'
	end
	def add_product
		if !request.get?
		    #检验产品型号是否重复
		    #p = Product.find_by_serial(params[:product][:serial])
                    p = Product.find_by_sql("select serial from products where serial='#{params[:product][:serial]}' and name='#{params[:product][:name]}' LIMIT 1")
                    #debugger
		    if p != []
		        flash[:notice] = "<img src='/images/fail.gif'><font color='green'>#{params[:product][:serial]}--#{params[:product][:name]}产品已存在！</font>"
		    else
				product = Product.new(params[:product])
                                #debugger
                                if product.total_counts == nil
                                        product.total_counts=0
                                end

 				product.state = 1
 				product.save
 				#增加图片
 				if params[:productPicture][:picture1].size>0
 					productPicture = ProductPicture.new
 					productPicture.picture = params[:productPicture][:picture1]
 					productPicture.product_id = product.id
 					productPicture.save
 				end
 				if params[:productPicture][:picture2].size>0
 					productPicture = ProductPicture.new
	 				productPicture.picture = params[:productPicture][:picture2]
	 				productPicture.product_id = product.id
 					productPicture.save
 				end
 				if params[:productPicture][:picture3].size>0
 					productPicture = ProductPicture.new
 					productPicture.picture = params[:productPicture][:picture3]
 					productPicture.product_id = product.id
 					productPicture.save
 				end
 				if params[:productPicture][:picture4].size>0
 					productPicture = ProductPicture.new
 					productPicture.picture = params[:productPicture][:picture4]
 					productPicture.product_id = product.id
 					productPicture.save
 				end
 				if params[:productPicture][:picture5].size>0
 					productPicture = ProductPicture.new
 					productPicture.picture = params[:productPicture][:picture5]
 					productPicture.product_id = product.id
 					productPicture.save
 				end
 				if params[:productPicture][:picture6].size>0
 					productPicture = ProductPicture.new
 					productPicture.picture = params[:productPicture][:picture6]
 					productPicture.product_id = product.id
 					productPicture.save
 				end
 				#记录产品数量变化
				pti             = ProductTransactionItem.new
				pti.create_date = Time.now
				pti.type 		  = 'IN'
				pti.value		  = product.total_counts
				pti.product       = product
				pti.save
				#分配产品到默认进货仓库
				store                      = Store.find_first('in_type=1')
				storeProduct               = StoreProduct.new
				storeProduct.product       = product
				storeProduct.store         = store
				storeProduct.current_count = product.total_counts
				storeProduct.save
				flash[:notice] = "<img src='/images/ok.gif'><font color='green'>#{product.serial}--#{product.name}产品已添加！</font>"
			end
			
    		redirect_to(:action=>'add_product')
 		end
  	end 

  	def list_product
  		if request.get?
                        state = 1
                        if '0'.eql? params[:state]
                                state = 0
                        end 
                        @product_pages, @products = paginate(:products,:conditions=>"state = #{state}",:order=>'in_date_at DESC',:per_page => 20)
  		else
  			@product_pages, @products = paginate(:products,:conditions=>'state=1',:order=>'in_date_at DESC',:per_page => 20)
                        product_serial = params[:product_serial]
                        product_name = params[:product_name]
                        #conditions = 'state = 1'
                        conditions = ''
                        if product_name != nil && product_name != ''
                                conditions += "name like '%#{product_name}%'"
                        end
                        if product_serial != nil && product_serial != ''
                                if conditions != ''
                                        conditions += ' and '
                                end
                                #conditions += "serial like '%#{product_serial}%' and state=1"
                                conditions += "serial like '%#{product_serial}%'"
                        end
                        if !conditions.eql? ''
                                @product_pages, @products = paginate(:products,:conditions=>conditions,:per_page => 20)
                        else
                                @product_pages, @products = paginate(:products,:conditions=>'state=1',:per_page => 20)
                        end
                end
  	end
  	
  	def list_product_4_stock
  		if request.get?
    		@products = Product.find(:all,:conditions=>"state=1",:order=>'in_date_at DESC')
  		else
  			@products = Product.find(:all,:conditions=>'state=1',:order=>'in_date_at DESC')
    	    product_serial = params[:product_serial]
    	    product_name = params[:product_name]
    	    conditions = ''
    	    if product_name != nil && product_name != ''
    	    	conditions += "name like '%#{product_name}%'"
    	    end
    	    if product_serial != nil && product_serial != ''
    	    	if conditions != ''
    	        	conditions += ' and '
				end
    	    	conditions += "serial like '%#{product_serial}%' and state=1"
    	    end
    	    if !conditions.eql? ''
    	    	@products = Product.find(:all,:conditions=>conditions)
    	    else
    	    	@products = Product.find(:all,:conditions=>'state=1',:order=>'in_date_at DESC')
    	    end
  		end
  	end
  	
    def stock
  		@product = Product.find(params[:id])
  		if !request.get?
  			#修改产品数量
  			@product.total_counts = @product.total_counts + params[:stock_num].to_f
			@product.in_date_at = Time.now
                        @product.update
  			#记录产品数量变化
			pti             = ProductTransactionItem.new
			pti.create_date = Time.now
			pti.type 		  = 'AD'
			pti.value		  = params[:stock_num].to_f
			pti.product       = @product
			pti.save
			#分配产品到默认进货仓库
			store                      = Store.find_first('in_type=1')
			storeProduct               = StoreProduct.find_first("store_id=#{store.id} and product_id=#{params[:id]}")
			if storeProduct
				storeProduct.current_count = storeProduct.current_count + params[:stock_num].to_f
			else
				storeProduct               = StoreProduct.new
				storeProduct.product_id       = params[:id]
				storeProduct.store         = store
				storeProduct.current_count = params[:stock_num].to_f
			end
			storeProduct.save
			flash[:notice] = "<img src='/images/ok.gif'><font color='green'>#{@product.name}--#{@product.name}产品增加库存处理完成！</font>"
  		end
  	end
  	
  	def show_product
  		@product = Product.find(params[:id])
  		@pp1=@product.productPictures[0] if @product.productPictures[0]
  		@pp2=@product.productPictures[1] if @product.productPictures[1]
  		@pp3=@product.productPictures[2] if @product.productPictures[2]
  		@pp4=@product.productPictures[3] if @product.productPictures[3]
  		@pp5=@product.productPictures[4] if @product.productPictures[4]
  		@pp6=@product.productPictures[5] if @product.productPictures[5]
  	end
  	
  	def product_info
  		show_product
  	end
  	
  	def stop_product
  		Product.update(params[:id],:state=>0)
  		redirect_to(:action=>'list_product')
  	end

  	def restart_product
  		Product.update(params[:id],:state=>1)
  		redirect_to(:action=>'list_product')
  	end
  	
  	def edit_product
  		if request.get?
  			show_product
  		else
  		  	sumCount = StoreProduct.find_by_sql("select sum(current_count) as count from store_products where product_id=#{params[:product_id]}")
  			#if sumCount[0].count.to_i != params[:product_total_counts].to_i
  				#flash[:notice] = "<img src='/images/ok.gif'><font color='green'>#{params[:product_name]}产品库存量与总数量不相等,不能完成修改！</font>"
                        p = Product.find_by_serial(params[:product_serial])
                        if p == nil || p.id != params[:product_id].to_i
                            flash[:notice] = "<img src='/images/fail.gif'><font color='green'>#{params[:product_serial]}产品已存在,不能完成修改!</font>"
  			else
  				#tmpDate = params[:date][:year]+'-'+params[:date][:month]+'-'+params[:date][:day]
  				product = Product.find(params[:product_id])
  				#增加产品变动记录
  				if product.total_counts != params[:product_total_counts].to_f
  					pti 			  = ProductTransactionItem.new
  					pti.create_date = Time.now
  					pti.type 		  = 'MA'
  					pti.value		  = params[:product_total_counts].to_f - product.total_counts
  					pti.product_id  = params[:product_id]
  					pti.save
  				end
  				product = Product.update(params[:product_id],:factory=>params[:product_factory],:brand=>params[:product_brand],:serial=>params[:product_serial],:name=>params[:product_name],:argument=>params[:product_argument],:agent_price=>params[:product_agent_price],:in_price=>params[:product_in_price],:sale_price=>params[:product_sale_price],:announce_price=>params[:product_announce_price],:total_counts=>params[:product_total_counts],:memo=>params[:product_memo],:in_date_at=>params[:in_date_at],:F=>params[:product_F],:B=>params[:product_B],:P=>params[:product_P])
				pp = product.productPictures
				if pp[0] && params[:productPicture][:picture1].size>0
					pp[0].picture = params[:productPicture][:picture1]
					pp[0].save
				elsif params[:productPicture][:picture1].size>0
					pp = ProductPicture.new
					pp.picture = params[:productPicture][:picture1]
					pp.product_id  = params[:product_id]
					pp.save
				end
				if pp[1] && params[:productPicture][:picture2].size>0
					pp[1].picture = params[:productPicture][:picture2]
					pp[1].save
				elsif params[:productPicture][:picture2].size>0
					pp = ProductPicture.new
					pp.picture = params[:productPicture][:picture2]
					pp.product_id  = params[:product_id]
					pp.save
				end
				if pp[2] && params[:productPicture][:picture3].size>0
					pp[2].picture = params[:productPicture][:picture3]
					pp[2].save
				elsif params[:productPicture][:picture3].size>0
					pp = ProductPicture.new
					pp.picture = params[:productPicture][:picture3]
					pp.product_id  = params[:product_id]
					pp.save
				end
				if pp[3] && params[:productPicture][:picture4].size>0
					pp[3].picture = params[:productPicture][:picture4]
					pp[3].save
				elsif params[:productPicture][:picture4].size>0
					pp = ProductPicture.new
					pp.picture = params[:productPicture][:picture4]
					pp.product_id  = params[:product_id]
					pp.save
				end
				if pp[4] && params[:productPicture][:picture5].size>0
					pp[4].picture = params[:productPicture][:picture5]
					pp[4].save
				elsif params[:productPicture][:picture5].size>0
					pp = ProductPicture.new
					pp.picture = params[:productPicture][:picture5]
					pp.product_id  = params[:product_id]
					pp.save
				end
				if pp[5] && params[:productPicture][:picture6].size>0
					pp[5].picture = params[:productPicture][:picture6]
					pp[5].save
				elsif params[:productPicture][:picture6].size>0
					pp = ProductPicture.new
					pp.picture = params[:productPicture][:picture6]
					pp.product_id  = params[:product_id]
					pp.save
				end

  				if product
  					flash[:notice] = "<img src='/images/ok.gif'><font color='green'>#{product.serial}---#{product.name}产品信息已修改！</font>"
  				end
  			end
  			redirect_to(:action=>'list_product')
  		end
  	end
  	
  	def list_storeProduct
                #debugger
  		@stores     = Store.find(:all,:conditions=>["state='OP'"])
  		@type       =	params[:type]
  		@type = 'move' if !@type
  		storeId     = params[:storeid]
  		productName = params[:product_name]
                productSerial = params[:product_serial] 
                if storeId
                    @storeProducts = StoreProduct.find(:all,:conditions=>"store_id=#{storeId}")
                else
                    @storeProducts = StoreProduct.find(:all,:conditions=>"product_id in (select id from products where products.name like '%#{productName}%' and products.serial like '%#{productSerial}%') and store_id in (select id from stores where state='OP')")
                end
        end
  	
  	def list_storeProduct_4_move
  		@stores     = Store.find(:all,:conditions=>["state='OP'"])
  		@type       =	'move'
  		render :template=>'product/list_storeProduct'
  	end
  	
  	def list_storeProduct_4_change
  		@stores     = Store.find(:all,:conditions=>["state='OP'"])
  		@type       =	'change'
  		render :template=>'product/list_storeProduct'
  	end
  	
  	def move_to
  		@storeProduct = StoreProduct.find(params[:spid])
  		currentValue = 0
		currentValue = @storeProduct.current_count if @storeProduct
  		@stores       = Store.find(:all,:conditions=>["state='OP'"])	
  		from  = params[:spid]
  		to    = params[:to]
  		value = params[:value]
  		if to
  			if currentValue < value.to_f
  				flash[:notice] = "<img src='/images/fail.gif'><font color='red'>#{@storeProduct.store.name}中的#{@storeProduct.product.serial}--#{@storeProduct.product.name}产品数量不足#{value}（kpcs）,不能完成此次调配</font>"
  			else
  				tmpStoreProduct = StoreProduct.find_first("product_id=#{@storeProduct.product_id} and store_id=#{to}")
  				if tmpStoreProduct
  					tmpStoreProduct.current_count += value.to_f
  				else
  					tmpStoreProduct = StoreProduct.new
					tmpStoreProduct.product       = @storeProduct.product
					tmpStoreProduct.store_id         = to.to_i
					tmpStoreProduct.current_count = value.to_f
  				end
  				tmpStoreProduct.save
  				@storeProduct.current_count -= value.to_f
  				@storeProduct.save
  				#记录库存变动记录
  				storeTransactionItemOut = StoreTransactionItem.new
  				storeTransactionItemOut.current_count = 0 - value.to_f
  				storeTransactionItemOut.type = 'CH'
  				storeTransactionItemOut.create_date_at = Time.now
  				storeTransactionItemOut.storeProduct = @storeProduct
  				storeTransactionItemOut.employee_id = @session[:account].employee.id
  				storeTransactionItemOut.save
  				storeTransactionItemIn = StoreTransactionItem.new
  				storeTransactionItemIn.current_count = value.to_f
  				storeTransactionItemIn.type = 'CH'
  				storeTransactionItemIn.create_date_at = Time.now
  				storeTransactionItemIn.storeProduct = tmpStoreProduct
  				storeTransactionItemIn.employee_id = @session[:account].employee.id
  				storeTransactionItemIn.save
  				#记录库存账目
  				storeTransaction = StoreTransaction.new
  				storeTransaction.from = @storeProduct
  				storeTransaction.to = tmpStoreProduct
  				storeTransaction.current_count = value.to_f
  				storeTransaction.employee_id = @session[:account].employee.id
  				storeTransaction.create_date_at = Time.now
  				storeTransaction.trtype='CH'
  				storeTransaction.product=@storeProduct.product
  				storeTransaction.save
  				
  				flash[:notice] = "<img src='/images/ok.gif'><font color='green'>产品#{@storeProduct.product.name}已经成功从#{@storeProduct.store.name}调配至#{storeTransactionItemIn.storeProduct.store.name}调配数量为：#{value}（kpcs）</font>"
  				redirect_to(:action=>'list_storeProduct')
  			end
  		end
  	end
  	
  	def change
  		@storeProduct = StoreProduct.find(params[:spid])	
                @Product = Product.find(:all,:conditions=>"id in (select product_id from store_products where product_id=#{@storeProduct.product.id} )")
  		value         = params[:value]
                #debugger
  		if value
  			storeTransactionItem = StoreTransactionItem.new
  			storeTransactionItem.current_count = value.to_f - @storeProduct.current_count
  			storeTransactionItem.type = 'MA'
  			storeTransactionItem.create_date_at = Time.now
  			storeTransactionItem.storeProduct = @storeProduct
  			storeTransactionItem.save
  			@storeProduct.current_count = value.to_f
                        #@Product[0].total_counts = @Product[0].total_counts+value.to_f
  			if @storeProduct.save
                                @sumTotalcounts = StoreProduct.find_by_sql("select sum(current_count) as a from store_products where product_id=#{@storeProduct.product.id}") 
                                #update products set total_counts = ( where id=#{@storeProduct.product.id}
                                @Product[0].total_counts = @sumTotalcounts[0].a.to_f
                                @Product[0].update
  				flash[:notice] = "<img src='/images/ok.gif'><font color='green'>产品#{@storeProduct.product.name}--#{@storeProduct.product.name}在#{@storeProduct.store.name}中的数量已经成功修改为#{value}（kpcs）</font>"
  			else
  				flash[:notice] = '操作失败'
  			end
  			redirect_to(:action=>'list_storeProduct_4_change')

                        #Product.update();
  		end
  	end
end
